<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>智能家居控制中心</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.8.1/prop-types.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.2/babel.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/recharts/2.15.0/Recharts.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
</head>
<body class="bg-gray-50 font-sans" style="font-family: 'Inter', sans-serif;">
  <div id="root" className="container mx-auto px-4 py-8 max-w-6xl"></div>

  <script type="text/babel">
    function SmartHomeControl() {
      const [priceData, setPriceData] = React.useState(null);
      const [sensorData, setSensorData] = React.useState({ light: 400, temperature: 30, humidity: 35 });
      const [command, setCommand] = React.useState({
        paras: {
          open_soil: false,
          open_fan: false,
          open_water: false,
          open_led: false,
          led_red: 0,
          led_green: 0,
          led_blue: 0,
          gather: false,
          id: '1'
        },
        service_id: 'Switch',
        command_name: 'control'
      });
      const [costData, setCostData] = React.useState({ before: { cost: 0, power: 0 }, after: { cost: 0, power: 0 } });
      const [loading, setLoading] = React.useState(true);
      const [error, setError] = React.useState(null);
      const [isModalOpen, setIsModalOpen] = React.useState(false);
      const [tempRGB, setTempRGB] = React.useState({ red: 0, green: 0, blue: 0 });
      const [status, setStatus] = React.useState('');
      const [devices, setDevices] = React.useState([]);
      const [selectedDeviceId, setSelectedDeviceId] = React.useState('1');

      // 加载设备列表
      React.useEffect(() => {
        const fetchDevices = async () => {
          try {
            const response = await fetch('/api/device/list');
            if (!response.ok) throw new Error('获取设备列表失败');
            const data = await response.json();
            setDevices(data.devices);
            if (data.devices.length > 0 && !selectedDeviceId) {
              setSelectedDeviceId(data.devices[0].id);
            }
          } catch (err) {
            console.error('获取设备列表失败:', err.message);
            setError(err.message);
          }
        };
        fetchDevices();
      }, []);

      // 加载设备状态和数据
      React.useEffect(() => {
        const fetchData = async () => {
          if (!selectedDeviceId) return;
          try {
            setLoading(true);
            // 获取电价
            const priceResponse = await fetch('/api/price/current');
            if (!priceResponse.ok) throw new Error('获取电价失败');
            const price = await priceResponse.json();
            setPriceData(price);

            // 获取设备状态
            const deviceResponse = await fetch(`/api/device/info?device_id=${selectedDeviceId}`);
            if (!deviceResponse.ok) throw new Error('获取设备状态失败');
            const deviceData = await deviceResponse.json();
            const newCommand = {
              paras: {
                open_soil: deviceData.soil > 0,
                open_fan: deviceData.fan ?? false,
                open_water: deviceData.water ?? false,
                open_led: deviceData.led ?? false,
                led_red: deviceData.led_red ?? 0,
                led_green: deviceData.led_green ?? 0,
                led_blue: deviceData.led_blue ?? 0,
                gather: deviceData.soil > 0,
                id: selectedDeviceId
              },
              service_id: 'Switch',
              command_name: 'control'
            };
            setCommand(newCommand);
            setSensorData({
              light: deviceData.light ?? 400,
              temperature: deviceData.temperature ?? 30,
              humidity: deviceData.humidity ?? 35
            });

            // 计算成本
            const costResponse = await fetch('/api/cost/calculate', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ command: newCommand })
            });
            if (!costResponse.ok) throw new Error('计算成本失败');
            const cost = await costResponse.json();
            setCostData(cost);
            setLoading(false);
          } catch (err) {
            console.error('数据获取失败:', err.message);
            setError(err.message);
            setLoading(false);
          }
        };
        fetchData();
        const interval = setInterval(fetchData, 60000);
        return () => clearInterval(interval);
      }, [selectedDeviceId]);

      const handleSensorChange = async (e) => {
        const { name, value } = e.target;
        const newSensorData = { ...sensorData, [name]: parseFloat(value) || 0 };
        setSensorData(newSensorData);
        try {
          const response = await fetch('/api/cost/sensor/update', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ id: selectedDeviceId, ...newSensorData })
          });
          if (!response.ok) throw new Error('更新传感器数据失败');
          console.log('传感器数据已发送:', newSensorData);
        } catch (err) {
          console.error('发送传感器数据失败:', err.message);
        }
      };

      const handleCommandChange = async (key, value) => {
        if (!selectedDeviceId) {
          setStatus('请先选择设备');
          return;
        }
        const newCommand = {
          ...command,
          paras: { ...command.paras, [key]: value, id: selectedDeviceId }
        };
        setCommand(newCommand);
        try {
          const response = await fetch('/api/remote_control', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(newCommand)

          });
          const result = await response.json();
          if (response.ok) {
            setStatus(`${new Date().toLocaleTimeString()} 设备${key}状态更新为: ${value ? '开启' : '关闭'}`);
          } else {
            throw new Error(result.message || '设备控制请求失败');
          }

          const costResponse = await fetch('/api/cost/calculate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ command: newCommand })
          });
          if (!costResponse.ok) throw new Error('计算成本失败');
          const cost = await costResponse.json();
          setCostData(cost);
        } catch (err) {
          console.error('设备控制或成本计算失败:', err.message);
          setStatus(`设备控制失败：${err.message}`);
        }
      };

      const openRGBModal = () => {
        if (!selectedDeviceId) {
          setStatus('请先选择设备');
          return;
        }
        setTempRGB({
          red: command.paras.led_red,
          green: command.paras.led_green,
          blue: command.paras.led_blue
        });
        setIsModalOpen(true);
      };

      const handleRGBChange = (color, value) => {
        setTempRGB({ ...tempRGB, [color]: parseInt(value) });
      };

      const confirmRGB = async () => {
        if (!selectedDeviceId) {
          setStatus('请先选择设备');
          return;
        }
        const newCommand = {
          ...command,
          paras: {
            ...command.paras,
            led_red: tempRGB.red,
            led_green: tempRGB.green,
            led_blue: tempRGB.blue,
            id: selectedDeviceId
          }
        };
        setCommand(newCommand);
        setIsModalOpen(false);
        try {
          const response = await fetch('/api/remote_control', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(newCommand)
          });
          const result = await response.json();
          if (response.ok) {
            setStatus(`${new Date().toLocaleTimeString()} RGB颜色设置为: R${tempRGB.red}, G${tempRGB.green}, B${tempRGB.blue}`);
          } else {
            throw new Error(result.message || 'RGB颜色设置请求失败');
          }

          const costResponse = await fetch('/api/cost/calculate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ command: newCommand })
          });
          if (!costResponse.ok) throw new Error('计算成本失败');
          const cost = await costResponse.json();
          setCostData(cost);
        } catch (err) {
          console.error('RGB颜色设置或成本计算失败:', err.message);
          setStatus(`RGB颜色设置失败：${err.message}`);
        }
      };

      const cancelRGB = () => {
        setIsModalOpen(false);
      };

      const handleDeviceChange = (deviceId) => {
        setSelectedDeviceId(deviceId);
      };

      if (loading) return (
        <div className="flex justify-center items-center h-screen">
          <div className="text-center">
            <div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-500 mx-auto mb-4"></div>
            <div className="text-xl text-blue-600">加载数据中...</div>
          </div>
        </div>
      );
      if (error) return (
        <div className="flex justify-center items-center h-screen">
          <div className="text-center text-red-500 text-xl">错误: {error}</div>
        </div>
      );

      const chartData = [
        { name: '调控前', cost: costData.before.cost },
        { name: '调控后', cost: costData.after.cost }
      ];
      const costReduction = costData.before.cost > 0
        ? ((costData.before.cost - costData.after.cost) / costData.before.cost * 100).toFixed(1)
        : 0;

      // 设备图标映射
      const deviceIcons = {
        '1': 'fa-house',
        '2': 'fa-thermometer',
        '3': 'fa-lightbulb',
        '4': 'fa-fan',
        '5': 'fa-droplet',
        '6': 'fa-plug',
        '7': 'fa-tv',
        '8': 'fa-camera'
      };

      return (
        <div className="space-y-8">
          <header className="text-center py-4">
            <h1 className="text-3xl md:text-4xl font-bold text-gray-800">
              <i className="fas fa-home text-blue-500 mr-3"></i>智能家居控制中心
            </h1>
            <p className="mt-2 text-gray-600">实时监控与优化您的家居能耗</p>
          </header>

          {/* 设备选择区域 - 图标形式 */}
          <div className="bg-white p-4 rounded-2xl shadow-md">
            <div className="flex items-center mb-4">
              <i className="fas fa-tablet-alt text-blue-500 text-xl mr-3"></i>
              <h2 className="text-xl font-bold text-gray-800">选择设备</h2>
            </div>
            <div className="flex flex-wrap justify-center gap-4">
              {devices.map(device => (
                <div
                  key={device.id}
                  onClick={() => handleDeviceChange(device.id)}
                  className={`flex flex-col items-center p-4 rounded-xl cursor-pointer transition-all duration-200 ease-in-out w-24 ${
                    selectedDeviceId === device.id
                      ? 'bg-blue-100 border-2 border-blue-500'
                      : 'bg-white border border-gray-200 hover:bg-gray-50'
                  }`}
                >
                  <div className="text-3xl mb-3 text-blue-500">
                    <i className={`fas ${deviceIcons[device.id] || 'fa-microchip'}`}></i>
                  </div>
                  <div className="text-sm font-medium text-gray-700">设备 {device.id}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="bg-white p-6 rounded-2xl shadow-md">
            <div className="grid grid-cols-1 md:grid-cols-4 gap-5">
              <div className="bg-blue-50 p-4 rounded-xl border border-blue-100">
                <div className="flex items-center">
                  <div className="p-3 rounded-xl bg-blue-100 mr-3">
                    <i className="fas fa-clock text-blue-600 text-xl"></i>
                  </div>
                  <div>
                    <div className="text-gray-500 text-sm">当前时间</div>
                    <div className="font-medium text-gray-800">{new Date().toLocaleTimeString()}</div>
                  </div>
                </div>
              </div>

              <div className="bg-purple-50 p-4 rounded-xl border border-purple-100">
                <div className="flex items-center">
                  <div className="p-3 rounded-xl bg-purple-100 mr-3">
                    <i className="fas fa-bolt text-purple-600 text-xl"></i>
                  </div>
                  <div>
                    <div className="text-gray-500 text-sm">电价时段</div>
                    <div className="font-medium text-gray-800">{priceData.period}</div>
                    <div className="text-sm text-purple-600">{priceData.price} 元/千瓦时</div>
                  </div>
                </div>
              </div>

              <div className="bg-green-50 p-4 rounded-xl border border-green-100">
                <div className="flex items-center">
                  <div className="p-3 rounded-xl bg-green-100 mr-3">
                    <i className="fas fa-coins text-green-600 text-xl"></i>
                  </div>
                  <div>
                    <div className="text-gray-500 text-sm">成本节省</div>
                    <div className="font-medium text-green-600">{costReduction}%</div>
                    <div className="text-sm text-gray-600">
                      {costData.before.cost.toFixed(4)}元 → {costData.after.cost.toFixed(4)}元
                    </div>
                  </div>
                </div>
              </div>

              <div className="bg-teal-50 p-4 rounded-xl border border-teal-100">
                <div className="flex items-center">
                  <div className="p-3 rounded-xl bg-teal-100 mr-3">
                    <i className="fas fa-leaf text-teal-600 text-xl"></i>
                  </div>
                  <div>
                    <div className="text-gray-500 text-sm">节能模式</div>
                    <div className="font-medium text-teal-600">已启用</div>
                    <div className="text-sm text-gray-600">自动优化能耗</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="lg:col-span-1 bg-white p-6 rounded-2xl shadow-md">
              <div className="flex items-center mb-6">
                <i className="fas fa-microchip text-blue-500 text-xl mr-3"></i>
                <h2 className="text-xl font-bold text-gray-800">传感器数据</h2>
              </div>
              <div className="space-y-4">
                <div className="bg-gray-50 p-4 rounded-lg border border-gray-100">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-gray-600 flex items-center">
                      <i className="fas fa-sun mr-2 text-yellow-500"></i> 光照强度
                    </span>
                    <span className="font-mono bg-gray-100 px-2 py-1 rounded">{sensorData.light} lux</span>
                  </div>
                  <input
                    type="range"
                    name="light"
                    min="0"
                    max="1000"
                    value={sensorData.light}
                    onChange={handleSensorChange}
                    className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-blue-500"
                  />
                </div>
                <div className="bg-gray-50 p-4 rounded-lg border border-gray-100">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-gray-600 flex items-center">
                      <i className="fas fa-thermometer-half mr-2 text-red-500"></i> 温度
                    </span>
                    <span className="font-mono bg-gray-100 px-2 py-1 rounded">{sensorData.temperature}°C</span>
                  </div>
                  <input
                    type="range"
                    name="temperature"
                    min="10"
                    max="40"
                    value={sensorData.temperature}
                    onChange={handleSensorChange}
                    className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-red-500"
                  />
                </div>
                <div className="bg-gray-50 p-4 rounded-lg border border-gray-100">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-gray-600 flex items-center">
                      <i className="fas fa-tint mr-2 text-blue-400"></i> 湿度
                    </span>
                    <span className="font-mono bg-gray-100 px-2 py-1 rounded">{sensorData.humidity}%</span>
                  </div>
                  <input
                    type="range"
                    name="humidity"
                    min="0"
                    max="100"
                    value={sensorData.humidity}
                    onChange={handleSensorChange}
                    className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-cyan-500"
                  />
                </div>
              </div>
            </div>

            <div className="lg:col-span-2 bg-white p-6 rounded-2xl shadow-md">
              <div className="flex items-center mb-6">
                <i className="fas fa-chart-bar text-purple-500 text-xl mr-3"></i>
                <h2 className="text-xl font-bold text-gray-800">成本对比分析</h2>
              </div>
              <div className="bg-gray-50 p-4 rounded-lg border border-gray-100">
                <Recharts.ResponsiveContainer width="100%" height={300}>
                  <Recharts.BarChart data={chartData} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
                    <Recharts.CartesianGrid strokeDasharray="3 3" stroke="#e0e0e0" />
                    <Recharts.XAxis dataKey="name" stroke="#666" />
                    <Recharts.YAxis stroke="#666" label={{ value: '成本 (元/小时)', angle: -90, position: 'insideLeft', fill: '#666' }} />
                    <Recharts.Tooltip
                      contentStyle={{ backgroundColor: '#fff', border: '1px solid #ddd', borderRadius: '8px', boxShadow: '0 4px 12px rgba(0,0,0,0.1)' }}
                      formatter={(value) => [`${value.toFixed(4)} 元`, '成本']}
                      labelStyle={{ color: '#333' }}
                    />
                    <Recharts.Bar
                      dataKey="cost"
                      name="成本"
                      fill="#4f46e5"
                      radius={[6, 6, 0, 0]}
                    >
                      <Recharts.LabelList dataKey="cost" position="top" formatter={(value) => value.toFixed(4) + '元'} fill="#444" />
                    </Recharts.Bar>
                  </Recharts.BarChart>
                </Recharts.ResponsiveContainer>
                <div className="mt-6 grid grid-cols-2 gap-4">
                  <div className="bg-blue-50 p-4 rounded-lg border border-blue-100">
                    <div className="text-center text-gray-600">调控前成本</div>
                    <div className="text-2xl text-center font-bold text-blue-600">{costData.before.cost.toFixed(4)} 元/小时</div>
                    <div className="text-center text-sm text-gray-600">功耗: {costData.before.power.toFixed(2)} W</div>
                  </div>
                  <div className="bg-green-50 p-4 rounded-lg border border-green-100">
                    <div className="text-center text-gray-600">调控后成本</div>
                    <div className="text-2xl text-center font-bold text-green-600">{costData.after.cost.toFixed(4)} 元/小时</div>
                    <div className="text-center text-sm text-gray-600">功耗: {costData.after.power.toFixed(2)} W</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="bg-white p-6 rounded-2xl shadow-md">
            <div className="flex items-center mb-6">
              <i className="fas fa-sliders-h text-blue-500 text-xl mr-3"></i>
              <h2 className="text-xl font-bold text-gray-800">设备远程控制</h2>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              {/* 土壤传感器卡片 */}
              <div className="bg-green-50 p-5 rounded-xl border border-green-200 relative overflow-hidden">
                <div className="absolute -top-2 -right-2 w-16 h-16 bg-green-100 rounded-full opacity-20"></div>
                <div className="flex items-center mb-4 z-10 relative">
                  <div className="p-2 bg-green-100 rounded-lg mr-2">
                    <i className="fas fa-seedling text-green-600 text-xl"></i>
                  </div>
                  <h3 className="font-semibold text-gray-700">土壤传感器</h3>
                  <div className="ml-auto">
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={command.paras.open_soil}
                        onChange={(e) => handleCommandChange('open_soil', e.target.checked)}
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-green-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-600"></div>
                    </label>
                  </div>
                </div>
                <div className="text-center py-6 z-10 relative">
                  <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-white border-4 border-green-200 mb-4">
                    <i className={`fas fa-seedling text-4xl ${command.paras.open_soil ? 'text-green-600' : 'text-gray-300'}`}></i>
                  </div>
                  <div className={`text-sm font-medium ${command.paras.open_soil ? 'text-green-600' : 'text-gray-500'}`}>
                    {command.paras.open_soil ? '工作中' : '已关闭'}
                  </div>
                </div>
              </div>

              {/* 风扇卡片 */}
              <div className="bg-blue-50 p-5 rounded-xl border border-blue-200 relative overflow-hidden">
                <div className="absolute -top-2 -right-2 w-16 h-16 bg-blue-100 rounded-full opacity-20"></div>
                <div className="flex items-center mb-4 z-10 relative">
                  <div className="p-2 bg-blue-100 rounded-lg mr-2">
                    <i className="fas fa-fan text-blue-600 text-xl"></i>
                  </div>
                  <h3 className="font-semibold text-gray-700">风扇</h3>
                  <div className="ml-auto">
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={command.paras.open_fan}
                        onChange={(e) => handleCommandChange('open_fan', e.target.checked)}
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                    </label>
                  </div>
                </div>
                <div className="text-center py-6 z-10 relative">
                  <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-white border-4 border-blue-200 mb-4">
                    <i className={`fas fa-fan text-4xl ${command.paras.open_fan ? 'text-blue-600 animate-spin' : 'text-gray-300'}`}></i>
                  </div>
                  <div className={`text-sm font-medium ${command.paras.open_fan ? 'text-blue-600' : 'text-gray-500'}`}>
                    {command.paras.open_fan ? '运行中' : '已关闭'}
                  </div>
                </div>
              </div>

              {/* 水泵卡片 */}
              <div className="bg-cyan-50 p-5 rounded-xl border border-cyan-200 relative overflow-hidden">
                <div className="absolute -top-2 -right-2 w-16 h-16 bg-cyan-100 rounded-full opacity-20"></div>
                <div className="flex items-center mb-4 z-10 relative">
                  <div className="p-2 bg-cyan-100 rounded-lg mr-2">
                    <i className="fas fa-faucet text-cyan-600 text-xl"></i>
                  </div>
                  <h3 className="font-semibold text-gray-700">水泵</h3>
                  <div className="ml-auto">
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={command.paras.open_water}
                        onChange={(e) => handleCommandChange('open_water', e.target.checked)}
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-cyan-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-cyan-600"></div>
                    </label>
                  </div>
                </div>
                <div className="text-center py-6 z-10 relative">
                  <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-white border-4 border-cyan-200 mb-4">
                    <i className={`fas fa-faucet text-4xl ${command.paras.open_water ? 'text-cyan-600 animate-pulse' : 'text-gray-300'}`}></i>
                  </div>
                  <div className={`text-sm font-medium ${command.paras.open_water ? 'text-cyan-600' : 'text-gray-500'}`}>
                    {command.paras.open_water ? '工作中' : '已关闭'}
                  </div>
                </div>
              </div>

              {/* LED灯卡片 */}
              <div className="bg-purple-50 p-5 rounded-xl border border-purple-200 relative overflow-hidden">
                <div className="absolute -top-2 -right-2 w-16 h-16 bg-purple-100 rounded-full opacity-20"></div>
                <div className="flex items-center mb-4 z-10 relative">
                  <div className="p-2 bg-purple-100 rounded-lg mr-2">
                    <i className="fas fa-lightbulb text-purple-600 text-xl"></i>
                  </div>
                  <h3 className="font-semibold text-gray-700">LED灯</h3>
                  <div className="ml-auto">
                    <label className="relative inline-flex items-center cursor-pointer">
                      <input
                        type="checkbox"
                        checked={command.paras.open_led}
                        onChange={(e) => handleCommandChange('open_led', e.target.checked)}
                        className="sr-only peer"
                      />
                      <div className="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                    </label>
                  </div>
                </div>
                <div className="text-center py-6 z-10 relative">
                  <div className="inline-flex items-center justify-center w-20 h-20 rounded-full bg-white border-4 border-purple-200 mb-4">
                    <i className={`fas fa-lightbulb text-4xl ${command.paras.open_led ? 'text-purple-600' : 'text-gray-300'}`}></i>
                  </div>
                  <div className="mt-4">
                    <button
                      onClick={openRGBModal}
                      className="px-4 py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors flex items-center justify-center w-full"
                    >
                      <i className="fas fa-palette mr-2"></i>
                      设置RGB颜色
                    </button>
                  </div>
                </div>
              </div>
            </div>
            <div className="mt-6 text-center text-gray-600" id="status">{status}</div>
          </div>

          {isModalOpen && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
              <div className="bg-white p-6 rounded-2xl shadow-xl w-full max-w-md">
                <h2 className="text-xl font-bold text-gray-800 mb-4">选择 RGB 颜色</h2>
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm text-gray-600 mb-1 flex items-center">
                      <span className="w-3 h-3 bg-red-500 rounded-full mr-2"></span>红光
                    </label>
                    <input
                      type="range"
                      min="0"
                      max="255"
                      value={tempRGB.red}
                      onChange={(e) => handleRGBChange('red', e.target.value)}
                      className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-red-500"
                    />
                    <div className="text-right text-sm mt-1 text-gray-600">{tempRGB.red}</div>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1 flex items-center">
                      <span className="w-3 h-3 bg-green-500 rounded-full mr-2"></span>绿光
                    </label>
                    <input
                      type="range"
                      min="0"
                      max="255"
                      value={tempRGB.green}
                      onChange={(e) => handleRGBChange('green', e.target.value)}
                      className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-green-500"
                    />
                    <div className="text-right text-sm mt-1 text-gray-600">{tempRGB.green}</div>
                  </div>
                  <div>
                    <label className="block text-sm text-gray-600 mb-1 flex items-center">
                      <span className="w-3 h-3 bg-blue-500 rounded-full mr-2"></span>蓝光
                    </label>
                    <input
                      type="range"
                      min="0"
                      max="255"
                      value={tempRGB.blue}
                      onChange={(e) => handleRGBChange('blue', e.target.value)}
                      className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-blue-500"
                    />
                    <div className="text-right text-sm mt-1 text-gray-600">{tempRGB.blue}</div>
                  </div>
                </div>
                <div className="mt-6 flex justify-end space-x-2">
                  <button
                    onClick={confirmRGB}
                    className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                  >
                    确认
                  </button>
                  <button
                    onClick={cancelRGB}
                    className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
                  >
                    取消
                  </button>
                </div>
              </div>
            </div>
          )}

          <footer className="text-center text-gray-500 text-sm py-6">
            <p>智能家居控制系统 © 2025 | 实时监控与优化您的家居能耗</p>
          </footer>
        </div>
      );
    }

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<SmartHomeControl />);
  </script>

  <style>
    body {
      background: linear-gradient(to bottom, #f9fafb, #f0f4f8);
      min-height: 100vh;
    }
    input[type="range"]::-webkit-slider-thumb {
      -webkit-appearance: none;
      appearance: none;
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background: #3b82f6;
      cursor: pointer;
      border: 2px solid white;
      box-shadow: 0 0 3px rgba(0,0,0,0.3);
    }
    input[type="range"]::-moz-range-thumb {
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background: #3b82f6;
      cursor: pointer;
      border: 2px solid white;
      box-shadow: 0 0 3px rgba(0,0,0,0.3);
    }
    .accent-blue-500::-webkit-slider-thumb { background: #3b82f6; }
    .accent-red-500::-webkit-slider-thumb { background: #ef4444; }
    .accent-green-500::-webkit-slider-thumb { background: #22c55e; }
    .accent-cyan-500::-webkit-slider-thumb { background: #06b6d4; }
    .accent-purple-500::-webkit-slider-thumb { background: #8b5cf6; }

    /* 设备卡片动画 */
    .device-card {
      transition: all 0.3s ease;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
    }
    .device-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
    }
  </style>
</body>
</html>